package cn.lds.health.controller;

import cn.lds.health.constant.DsHealthConstant;
import cn.lds.health.dto.ResultDTO;
import cn.lds.health.entity.User;
import cn.lds.health.exception.SysException;
import cn.lds.health.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.Objects;

/**
 * @ClassName UserController
 * @Description TODO
 * @Author Christopher
 * @Date 2023/8/7 08:36
 * @Version 1.0
 **/

@Controller
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	private UserService userService;
	
	private final static Logger log = LoggerFactory.getLogger(UserController.class);
	
	/**
	 * 编写跳转到登录页面方法
	 * @return
	 */
	@RequestMapping("/login")
	public String login(HttpSession session) throws SysException {
		if (session.getAttribute("user") != null){
			throw new SysException(DsHealthConstant.User.ALREADY_LOGGED);
		}
		return "login";
	}
	
	/**
	 * 接收用户登录请求，要求该方法必须使用post请求方式才能访问
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/do_login",method = RequestMethod.POST)
	public String doLogin(User user, Model model, HttpSession session){
		
		log.info("user:{}",user);
		
		ResultDTO<User> userResultDTO = userService.loginUser(user);
		
		if (userResultDTO.getCode().equals(4000)){
			model.addAttribute("msg",userResultDTO.getMsg());
			return "/login";
		}else {
			session.setAttribute("user",userResultDTO.getData());
			return "redirect:/";
		}
	}
	
	@RequestMapping("/logout")
	public String logout(HttpSession session){
		session.removeAttribute("user");
		return "redirect:/user/login";
	}
	
	/**
	 * 跳转到注册页面
	 * @return
	 */
	@RequestMapping("/reg")
	public String reg(){
		return "reg";
	}
	
	/**
	 * 接收注册请求 必须使用post方式提交
	 * @param user
	 * @return
	 * @throws SysException
	 */
	@RequestMapping(value = "/do_reg",method = RequestMethod.POST)
	public String doReg(User user) throws SysException {
		
		ResultDTO resultDTO = userService.regUser(user);
		
		return "redirect:/user/login";
	}
	
	@RequestMapping("/select_user_by_id_no_or_mobile_no")
	//直接返回对象字符串方式结果
	@ResponseBody
	public ResultDTO selectUserByIdNoORMobileNo(@RequestBody Map<String, String> map) throws SysException {
		
		log.info("map:{}",map);
		
		ResultDTO resultDTO = userService.selectUserByIdNoOrMobileNo(map.get("idNo"),map.get("mobileNo"));
		return resultDTO;
	}
}